<?php
/*
Copyright (C) 2009 de Flotte Maxence

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
?>
<?php
/**
 *	Translation type rules
 *	To translate all databases as possible
 */
	define('NO_END',-1);
	
	// Translation type rules
		//name																																	the type
		//										type																							translated type
		//																min size															must be bigger or equal at
		//																				max size											must be less or equal at
		//																									let choose size			the size is not determinable (false) or the default size
	$_mysqlType = array(
		'numeric'		=>	array(array('INT'			,0				,NO_END,	10,			0)),
		'date'			=>	array(array('INT'			,0				,NO_END,	10,			false)),
		'string'		=>	array(
													array('TEXT'		,NO_END		,NO_END,	false,	false),
													array('VARCHAR'	,0				,NO_END,	50,			false)
										),
		'bool'			=>	array(array('INT'			,0				,NO_END,	1,			0)),
		'float'			=>	array(array('DOUBLE'	,0				,NO_END,	true,		0))
	);
	$mysqlIdDeclaration = '`id` int(11) NOT NULL AUTO_INCREMENT';
	$mysqlRefDeclaration = '`id` int(11) NOT NULL,
	`user` int(11) NOT NULL';
	$GLOBALS['sqlTranslationRules'] = $_mysqlType;
	$GLOBALS['sqlIdDeclaration'] = $mysqlIdDeclaration;
	$GLOBALS['sqlRefDeclaration'] = $mysqlRefDeclaration;
?>
<?php //2RM
	include './conf.php';
	include './ZzL/autoload.php';
	$GLOBALS['cwd'] = getcwd();
	//translateDomaine('Domtest');
	//getAndTranslateDomains();
?>
<?php
/**
 *	This file, install and update database from domain files
 *	For now, just mysql database is suported
 */
?>
<?php

/**
 *	Get All domains and translate it
 */
	function getAndTranslateDomains($force = false) {
		$return = '';
		if ($handle = opendir('./ZzDom/')) {
			while (false !== ($file = readdir($handle))) {
					if ($file != '.' && $file != '..' && is_file('./ZzDom/'.$file)) {
							if($force)
								$return .= rmDomain(str_replace('.php','',ucfirst($file)));
							$return .= translateDomain(str_replace('.php','',ucfirst($file)));
					}
			}
			closedir($handle);
		}
		return nl2br($return);
	}

/**
 *	Get All domdatas and put it
 */
	function getAndPutDomDatas() {
		$return = '';
		if ($handle = opendir('./ZzDom/ZzDomData')) {
			while (false !== ($file = readdir($handle))) {
					if ($file != '.' && $file != '..' && is_file('./ZzDom/ZzDomData/'.$file)) {
						$return .= putDomData(str_replace(array('domdata','.php'),'',$file)).'
';
						//echo str_replace(array('domdata','.php'),'',$file),':';
					}
			}
			closedir($handle);
		}
		return nl2br($return);
	}

/**
 *	Drop a table
 */
	function rmDomain($domainName) {
		$tableName = $GLOBALS['prefix'].strToLower(preg_replace('!^dom!i','',$domainName));
		$query = 'DROP TABLE `'.$tableName.'`;
';
		ZzSQL::exec($query);
		//echo $query;
		return "Drop $domainName \n";
	}
/**
 *	Get DomData and put it on tables
 */
	function putDomData($domdata = null) {
		if(empty($domdata)) {
			$autoDetectDomain = true;
		}
		else {
			$autoDetectDomain = false;
			$domain = $domdata;
			}
		$domdataFile = 'ZzDom/ZzDomData/domdata'.$domdata.'.php';
		
		require $domdataFile;
		$query = '';
		
		
		foreach($data as $row) {
			//Detect domain
			if($autoDetectDomain)
				$domain = $row['type'];
			
			$obj = new ZzSQLWritingQueryGenerator($domain);
			
			foreach($row as $key => $col) {
				$obj->set($key, $col);
			}
			if($obj->validate())
				$obj->save();
			//$query = new  
			/*$dom = new $domain();
			$_tables = array();
			
			//Get tables and their values


			foreach($row as $key => $col) {
				if(!array_key_exists($dom->$key->dom,$_tables))
					$_tables[$dom->$key->dom] = array();
				$_tables[$dom->$key->dom][$key] = $col;
			}

			if(count($_tables)>1)
				foreach($_tables as $key => $_row) {
					$_tables[$key]['id'] = $row['id'];
					//echo $_tables[$key]['id'];
				}

			foreach($_tables as $name => $_row) {
				$query .=	'INSERT INTO `'.$GLOBALS['prefix'].$name.'`(';
				foreach($_row as $key => $col) {
					if($dom->$key->quoted)
						$col = '\''.addSlashes($col).'\'';
					if(!isSet($values)) {
						$values = $col;
						$query .= '`'.$key.'`';
					}
					else {
						$values .= ','.$col;
						$query .= ',`'.$key.'`';
					}
				}
				$query .= ') VALUES('.$values.');
';
				unset($values);
			}*/
		}
		return 'DomData :: '.$domdata.' OK'."\n";
	}
/**
 *	Translate a domain
 */
	function translateDomain($domainName) {
		$tableName = $GLOBALS['prefix'].strToLower(preg_replace('!^dom!i','',$domainName));
		$domain = new $domainName();
		$sql = $GLOBALS['sql'];
		$_allVars = array_keys(get_class_vars(get_class($domain)));
		if(get_parent_class($domain))
			$_parentVars = array_keys(get_class_vars(get_parent_class($domain)));
		else
			$_parentVars = array();
		$_rows = array_diff($_allVars, $_parentVars);
		$_refs = array();
		$_primary = array(); //Primary key list

		//Remove ref from $_rows, and add on $_refs
		foreach($_rows as $key => $var) {
			if(strToLower(get_parent_class($domain->$var))=='domref') {
				array_splice($_rows,$key,1);
				$_refs[] = $var;
			}
			if($domain->$var->primary) {
				$_primary[] = $var;
			}
		}
		$_refTables = array();
		foreach($_refs as $key => $var) {
			if(array_key_exists($domain->$var->dom.'_'.$domain->$var->ref,$_refs))
				$_refTables[$domain->$var->dom.'_'.$domain->$var->ref] = array();
			$_refTables[$domain->$var->dom.'_'.$domain->$var->ref][] = $var;
		}
			
			//echo '(',$domain->$var->name,', ',$domain->$var->sqlType,', ',intval($domain->$var->sqlLength),'), ';

		
		//The table exists ?
		$tableExist = is_object($sql->query('SELECT * FROM `'.$tableName.'`'));

		//Get table columns
		if($tableExist) {
			$_fieldToAdd = array();
			foreach($_rows as $var) {
				if(!is_object($sql->query('SELECT `'.$var.'` FROM `'.$tableName.'`')))
					$_fieldToAdd[] = $var;
			}
			$query = 'ALTER TABLE `'.$tableName.'`';
			$first = true;
			foreach($_fieldToAdd as $var) {
				if($first)
					$first = false;
				else
				$query .= ',';
				var_dump($domain->$var);
				$query .= '
	ADD `'.$var.'` '.getSQLType($domain->$var->sqlType,$domain->$var->sqlLength).(($domain->$var->nullable)?'':' NOT NULL ');
			}
			$query .= ';
';
		}
		else {
			if(count($_primary) == 0) {
				$query = 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` (
	'.$GLOBALS['sqlIdDeclaration'];
				$primaryList = '`id`';
				$a = true;
				//if(count($_rows) > 1) $query .= ',';
			}
			else {
				$query = 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` (';
				$primaryList = implode(',', array_map(create_function('$arg','return \'`\'.$arg.\'`\';'),$_primary));
				$a = false;
			}
			
			foreach($_rows as $var) {
				if($a == false) 
					$a = true;
				else
					$query .= ',';
				if($var != 'id')
					$query .= '
	`'.$var.'` '.getSQLType($domain->$var->sqlType,$domain->$var->sqlLength).(($domain->$var->nullable)?'':' NOT NULL');
				else
					$query .= '
	'.$GLOBALS['sqlIdDeclaration'];;
	
			}
			$query .= ',
	PRIMARY KEY ('.$primaryList.')
);
';

		}
		
		
		//Create domRef
		foreach($_refTables as $tableName => $rows) {
			$tableExist = is_object($sql->query('SELECT * FROM `'.$GLOBALS['prefix'].$tableName.'`'));
			
			if($tableExist) {
				$_fieldToAdd = array();
				foreach($rows as $var) {
					if(!is_object($sql->query('SELECT `'.$domain->$var->name.'` FROM `'.$GLOBALS['prefix'].$tableName.'`')))
						$_fieldToAdd[] = $var;
				}
				$query .= '

ALTER TABLE `'.$GLOBALS['prefix'].$tableName.'`';
				$first = true;
				foreach($_fieldToAdd as $var) {
					if($first)
						$first = false;
					else
					$query .= ',';
					$query .= '
	ADD `'.$domain->$var->name.'` '.getSQLType($domain->$var->sqlType,$domain->$var->sqlLength).' '.(($domain->$var->nullable)?'':'NOT NULL ');
				}
				$query .= ';
';
			}
			else {
				$query .= '

CREATE TABLE IF NOT EXISTS `'.$GLOBALS['prefix'].$tableName.'` (
	'.$GLOBALS['sqlRefDeclaration'];
				foreach($rows as $var) {
					$query .= ',
	`'.$domain->$var->name.'` '.getSQLType($domain->$var->sqlType,$domain->$var->sqlLength).' '.(($domain->$var->nullable)?'':'NOT NULL');
			}
				$query .= ',
	PRIMARY KEY (`id`,`user`)
);
';
			}
		}
	ZzSQL::exec($query);
	//echo $query;
	return "Translate $domainName\n";
	}
	
	function getSQLType($type,$length) {
		$rules = $GLOBALS['sqlTranslationRules'];
		foreach($rules[$type] as $rule) {
			if(((($length > $rule[1]) and ($rule[1] != NO_END)) or is_null($length) or $length == NO_END) and (($length < $rule[1]) or ($rule[2] == NO_END) or is_null($length))) {
				if(is_int($rule[3]))
					if(is_null($length) or $length == NO_END) {
						if($rule[4] === false)
							return $rule[0].'('.$rule[3].')';
						else
							return $rule[0].'('.$rule[3].') DEFAULT '.$rule[4];
						}
					else {
						if($rule[4] === false)
							return $rule[0].'('.intval($length).')';
						else
							return $rule[0].'('.intval($length).') DEFAULT '.$rule[4];
					}
				else {
					if($rule[4] === false)
						return  $rule[0];
					else
						return  $rule[0].'DEFAULT '.$rule[4];
				}
			}
		}
	}
?>